#include "execmd.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <signal.h>
#include <errno.h>

#include <unistd.h>     // included for `open`
#include <errno.h>      // included for `errno`
#include <string.h>     // inlcuded for `strerror`
#include <stdlib.h>     // included for `exit`
#include <sys/file.h>   // included for `flock`

static unsigned error_count = 0;

char* executeCMD(const char *cmd, char *result, unsigned result_size) {
    char buf_ps[1024];
    char ps[1024] = {'\0'};

    if(strlen(cmd) >= 1024) {
        fprintf(stderr, "----------------cmd is too long\n");
        return NULL;
    }

    FILE *ptr;
    strncpy(ps, cmd, strlen(cmd));

    if((ptr = popen(ps, "r")) != NULL) {

        while(fgets(buf_ps, 1024, ptr) != NULL) {
            if(strlen(result) + strlen(buf_ps) > result_size - 1)
                break;
            strcat(result, buf_ps);

            if(strlen(result) == (result_size - 1))
                break;
        }

        pclose(ptr);
        ptr = NULL;
    }else {
        //LOG(WARNING) << "popen "<< ps << " error";
        fprintf(stderr, "---------------------------------------popen fail.\n");
        memset(result, 0, sizeof(result));
        error_count++;
        if(10 <= error_count) {
            exit(-1);
        }
    }

    return result;
}

#if 0
int checkProcessExistStatus(int pid, const char* pname) {
    if(pid < 0 || NULL == pname) return -1;
    char path[32];
    memset(path, 0, 32);
    sprintf(path, "/proc/%d/cmdline", pid); // 构造 cmdline 文件路径

    FILE *fp = fopen(path, "r"); // 打开 cmdline 文件
    if (fp == NULL) {
        return 0;
    }

    char cmd[128];
    fgets(cmd, sizeof(cmd), fp); // 读取命令行参数
    fclose(fp);

    if (strstr(cmd, pname) != NULL) { // 如果命令行参数中包含 pname 字符串，则认为进程正在运行
        return 1;
    }

    return 0;
}
#endif

int checkProcessExistStatus(int pid, const char* pname) {
    if(pid < 0 || NULL == pname) return -1;
    if(0 == pid) return 0;
    int rc = kill(pid, 0);
    fprintf(stderr, "-----------pid %d, rc %d, errno %d\n", pid, rc, errno);
    if(rc < 0) {
        if(ESRCH == errno) {
            return 0;
        }
        return -2;
    }else {
        return 1;
    }
}

char *basename2(char *fullname) {
    char *p = rindex(fullname, '/');
    if(p == NULL)
        p = fullname;
    else
        p++;
    return p;
}

int isRunning(const char *pidfile) {
    int fd = -1;
    char buf[16] = { 0x00 };

    if (-1 == (fd = open(pidfile, O_RDWR | O_CREAT, 0666))) {
        fprintf(stderr, "can't open or create %s: %s\n",
                pidfile, strerror(errno));
        exit(1);
    }

    if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
        int save_errno = errno;
        if ((save_errno == EAGAIN) || (save_errno == EACCES)) {
            close(fd);
            return 1;
        }

        fprintf(stderr, "can't lock %s: %s\n", pidfile, strerror(save_errno));
        exit(1);
    }
    ftruncate(fd, 0);
    snprintf(buf, sizeof(buf) - 1, "%ld", (long)getpid());
    write(fd, buf, strlen(buf) + 1);
    return 0;
}